<template>
  <div class="app-container-custom">
    <el-row :gutter="10">
      <el-col :span="5" :xs="24">
        <el-card shadow="never">
          <org-tree ref="orgTree" modelType="'dept','community'" @nodeClick="handleNodeClick" @firstNodeClick="handleFirstNodeClick"/>
        </el-card>
      </el-col>
      <el-col :span="19" :xs="24">
        <el-card shadow="never">
          <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="代码" prop="normCode">
              <el-input v-model="queryParams.normCode" placeholder="请输入代码" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="名称" prop="normNames">
              <el-input v-model="queryParams.normNames" placeholder="请输入名称" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5"><el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['payfee:norm:add']">新增</el-button></el-col>
            <el-col :span="1.5">
              <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['payfee:norm:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['payfee:norm:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading" @click="handleExport" v-hasPermi="['payfee:norm:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>

          <el-table v-loading="loading" :data="normList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="代码" align="center" prop="normCode" />
            <el-table-column label="名称" align="center" prop="normNames" />
            <el-table-column label="组织机构" align="center" prop="deptName" />
            <el-table-column label="收费项目" align="center" prop="chargeName" />
            <el-table-column label="费用生成方式" align="center" prop="chargeGenerateType" :formatter="chargeGenerateTypeFormat"/>
            <!--<el-table-column label="收费时间" align="center" prop="chartimeNames" />-->
            <el-table-column label="抵扣单价" align="center" prop="deductionPrice" />
            <el-table-column label="单价" align="center" prop="prices" />
           <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['payfee:norm:edit']">修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['payfee:norm:remove']">删除</el-button>
              </template>
            </el-table-column>-->
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改收费标准对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="760px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
            <el-form-item label="代码" prop="normCode"><el-input v-model="form.normCode" placeholder="请输入代码" /></el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="名称" prop="normNames"><el-input v-model="form.normNames" placeholder="请输入名称" /></el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
            <el-form-item label="组织机构" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :normalizer="normalizer" :disable-branch-nodes="true" placeholder="选择组织机构" />
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="收费项目" prop="chargeId">
              <el-select v-model="form.chargeId" placeholder="请选择收费项目">
                <el-option v-for="dict in itemOptions" :key="dict.chargeId" :label="`${dict.chargeCode}-${dict.chargeName}`" :value="dict.chargeId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <!--<el-col :span="12" :xs="24">
            <el-form-item label="收费时间" prop="chartimId">
              <el-select v-model="form.chartimId" placeholder="请选择收费时间">
                <el-option v-for="dict in chartTimeOptions" :key="dict.chartimId" :label="dict.chartimeNames" :value="dict.chartimId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>-->
          <el-col :span="12" :xs="24">
            <el-form-item label="费用生成方式" prop="chargeGenerateType">
              <el-select v-model="form.chargeGenerateType" placeholder="请选择费用生成方式">
                <el-option v-for="dict in chargeGenerateTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="抵扣单价" prop="deductionPrice">
              <el-input-number v-model="form.deductionPrice" :precision="2" :step="0.1" :min="0"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
            <el-form-item label="单价" prop="prices"><el-input-number v-model="form.prices" :precision="2" :step="0.1" :min="0"></el-input-number></el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
            <el-form-item label="计算公式">
              <el-radio-group v-model="form.computingFormula">
                <template v-for="dict in computingFormulaOptions">
                  <el-radio style="margin: 0 10px 10px 0;" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel }}</el-radio>
                  <br/>
                </template>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="公式" prop="formula" v-if="form.computingFormula == '10010'"><el-input v-model="form.formula" placeholder="请输入公式" /></el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="说明" v-if="form.computingFormula== '10010'">
              <span>
                C 代表房屋对应小区面积<br/>
                F 代表房屋对应楼栋面积<br/>
                U 代表房屋对应单元面积<br/>
                R 代表房屋面积<br/>
                X 代表房屋收费系数（房屋管理中配置）<br/>
                L 代表房屋层数<br/>
                举例：电梯使用费 (层数-5)*每层单价+基础费用<br/>
                公式：(L-5)*5 + 10<br/>
              </span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listNorm, getNorm, delNorm, addNorm, updateNorm, exportNorm } from '@/api/payfee/norm';
import { orgTreeSelect } from '@/api/system/dept';
import { listItem } from '@/api/payfee/item';
import { listCharTime } from '@/api/payfee/CharTime';
export default {
  name: 'Norm',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 收费标准表格数据
      normList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 计算公式字典
      computingFormulaOptions: [],
      deptOptions: [],
      itemOptions: [],
      chartTimeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        normCode: null,
        normNames: null,
        currency: null,
        deptId: null,
        chargeId: null,
        chartimId: null,
        deductionPrice: null,
        prices: null,
        computingFormula: null,
        formula: null,
        chargeGenerateType:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        normCode: [{ required: true, message: '代码不能为空', trigger: 'blur' }],
        normNames: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        deptId: [{ required: true, message: '所属物业不能为空', trigger: 'blur' }],
        formula: [{ required: true, message: '公式不能为空', trigger: 'blur' }],
        chargeId: [{ required: true, message: '收费项目不能为空', trigger: 'blur' }],
        chargeGenerateType: [{ required: true, message: '费用生成方式不能为空', trigger: 'blur' }],
        /*chartimId: [{ required: true, message: '收费时间不能为空', trigger: 'blur' }],*/
      },
      //所有计算公式
      computingFormulaOptionsBack:[],
      chargeGenerateTypeOptions:[],
      costFormulaClassify:{
        '01':['10001','10002','10004','10005','10010'],//常规收费项目
        '02':['10003','10004','10005','10010'],//抄表收费项目
        '03':['10001','10010'],//临时收费项目
        '05':['10006','10007','10010'] //租赁收费项目
      },
    };
  },
  watch:{
    'form.chargeId'(v){
      if(v){
        let index = this.itemOptions.findIndex(x=>x.chargeId==v)
        if(index != -1){
          let row = this.itemOptions[index]
          if(row.projectId){
            this.changeFeeTypeCd(row.projectId)
          }
        }
      }
    }
  },
  created() {
    //this.getList();
    this.getDicts('computing_formula').then(response => {
      this.computingFormulaOptionsBack = response.data;
      this.changeFeeTypeCd('03');
    });
    this.getDicts("charge_generate_type").then(response => {
      this.chargeGenerateTypeOptions = response.data;
    });
  },
  methods: {
    /** 查询收费标准列表 */
    getList() {
      this.loading = true;
      listNorm(this.queryParams).then(response => {
        this.normList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    changeFeeTypeCd(v){
      this.computingFormulaOptions = [];
      for(let i in this.costFormulaClassify[v]){
        let vals = this.costFormulaClassify[v][i];
        let index = this.computingFormulaOptionsBack.findIndex(x=>x.dictValue == vals);
        if(index != -1){
          this.computingFormulaOptions.push(this.computingFormulaOptionsBack[index]);
        }
      }
    },
    getDeptList() {
      orgTreeSelect({modelType:"'dept','community'"}).then(response => {
        this.deptOptions = response.data;
      });
    },
    getItemList() {
      listItem().then(response => {
        this.itemOptions = response.rows;
      });
    },
    getcharTimeList() {
      listCharTime().then(response => {
        this.chartTimeOptions = response.rows;
      });
    },
    // 计算公式字典翻译
    computingFormulaFormat(row, column) {
      return this.selectDictLabel(this.computingFormulaOptions, row.computingFormula);
    },
    //费用生成方式字典翻译
    chargeGenerateTypeFormat(row, column) {
      return this.selectDictLabel(this.chargeGenerateTypeOptions, row.chargeGenerateType);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        normId: null,
        normCode: null,
        normNames: null,
        currency: null,
        deptId: null,
        chargeId: null,
        chartimId: null,
        deductionPrice: null,
        prices: null,
        computingFormula: '10001',
        formula: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.normId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '添加收费标准';
      if(this.currentNode.modelType == 'community'){
        this.form.deptId = this.currentNode.id
      }
      this.getDeptList();
      this.getItemList();
      this.getcharTimeList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getDeptList();
      this.getItemList();
      this.getcharTimeList();
      const normId = row.normId || this.ids;
      getNorm(normId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = '修改收费标准';
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.normId != null) {
            updateNorm(this.form).then(response => {
              this.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addNorm(this.form).then(response => {
              this.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const normIds = row.normId || this.ids;
      this.$confirm('是否确认删除收费标准编号为"' + normIds + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return delNorm(normIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess('删除成功');
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有收费标准数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.exportLoading = true;
          return exportNorm(queryParams);
        })
        .then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children
      };
    },
    handleNodeClick(node){
      this.currentNode = node;
      this.queryParams.nodeId = node.id
      this.getList()
    },
    handleFirstNodeClick(node){
      this.currentNode = node;
      this.queryParams.nodeId = node.id;
      this.getList();
    }
  }
};
</script>
